/*
 * @(#) MyInvocationSecurityMetadataSourceService.java 2011-3-23 下午02:58:29
 * Copyright 2011 by Sparta
 */

package com.plat.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import com.plat.service.IDictionaryGroupService;
import com.plat.util.SpringApplicationContextHolder;

/**
 * 最核心的地方，就是提供某个资源对应的权限定义，即getAttributes方法返回的结果。 此类在初始化时，应该取到所有资源及其对应角色的定义。
 */
@Service
public class CustomInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

	// @Autowired
	// private SysAuthoritiesResourcesDao pubAuthoritiesResourcesDao;

	private IDictionaryGroupService groupService;

	private AntPathMatcher urlMatcher = new AntPathMatcher();

	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	public CustomInvocationSecurityMetadataSourceService() {
		loadResourceDefine();
	}

	public void loadResourceDefine() {
		ApplicationContext context = SpringApplicationContextHolder.getApplicationContext();
		SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");

		groupService = (IDictionaryGroupService) context.getBean("dictionaryGroupServiceImpl");

		// 初始化数据字典
		groupService.initTypeGroups();

		Session session = sessionFactory.openSession();

		String sql = "";

		// 在Web服务器启动时，提取系统中的所有权限。
		sql = "select authority_id from sys_authorities";

		List<String> query = session.createSQLQuery(sql).list();

		/*
		 * 应当是资源为key， 权限为value。 资源通常为url， 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。 sparta
		 */
		resourceMap = new LinkedHashMap<String, Collection<ConfigAttribute>>();

		for (String auth : query) {
			ConfigAttribute ca = new SecurityConfig(auth);

			List<String> query1 = session.createSQLQuery(
					"select b.resource_string " + "from Sys_Authorities_Resources a, Sys_Resources b, "
							+ "Sys_authorities c where a.resource_id = b.resource_id "
							+ "and a.authority_id=c.authority_id and c.Authority_id='" + auth + "'").list();

			for (String res : query1) {
				String url = res;

				/*
				 * 判断资源文件和权限的对应关系，如果已经存在相关的资源url，则要通过该url为key提取出权限集合，将权限增加到权限集合中。 sparta
				 */
				if (resourceMap.containsKey(url)) {

					Collection<ConfigAttribute> value = resourceMap.get(url);
					value.add(ca);
					resourceMap.put(url, value);
				} else {
					Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
					atts.add(ca);
					resourceMap.put(url, atts);
				}

			}

		}
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {

		return null;
	}

	// 根据URL，找到相关的权限配置。
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

		// object 是一个URL，被用户请求的url。
		String url = ((FilterInvocation) object).getRequestUrl();

		int firstQuestionMarkIndex = url.indexOf("?");

		if (firstQuestionMarkIndex != -1) {
			url = url.substring(0, firstQuestionMarkIndex);
		}
		System.out.println("请求地址为:" + url);

		if (resourceMap.size() == 0) {
			loadResourceDefine();
		}

		Iterator<String> ite = resourceMap.keySet().iterator();

		while (ite.hasNext()) {
			String _url = ite.next();
			String urlTmp = _url;
			if (_url.indexOf("?") != -1) {
				_url = _url.substring(0, _url.indexOf("?"));
			}
			if (urlMatcher.match(_url, url))
				return resourceMap.get(urlTmp);
		}
		Collection<ConfigAttribute> returnCollection = new ArrayList<ConfigAttribute>();
		returnCollection.add(new SecurityConfig("AUTH_NO_USER"));
		return returnCollection;
	}

	@Override
	public boolean supports(Class<?> arg0) {

		return true;
	}

	public static void main(String[] args) {

	}
}
